S0="${BASH_SOURCE[0]}"
DIRNAME="$( dirname "$S0")"
DIR="$( cd "$DIRNAME" && pwd)"
echo $DIR/..

NODE="/usr/local/bin/node"
PYTHON="/Library/Frameworks/Python.framework/Versions/3.13/bin/python3"

WORKSPACE=${WORKSPACE:=$(realpath "$DIR/..")}
echo WORKSPACE=$WORKSPACE
export WORKSPACE

JOB_NAME=${JOB_NAME:=MANUAL}
echo JOB_NAME=$JOB_NAME
export JOB_NAME

BUILD_NUMBER=${BUILD_NUMBER:=1}
echo BUILD_NUMBER=$BUILD_NUMBER
export BUILD_NUMBER

GIT_COMMIT=${GIT_COMMIT:="'00000000'"}
echo GIT_COMMIT=${GIT_COMMIT}
SHORT_GIT_COMMIT=$(echo $GIT_COMMIT | cut -c 1-8)
echo SHORT_GIT_COMMIT=${SHORT_GIT_COMMIT}

$NODE $WORKSPACE/ci/create_configconst.js $WORKSPACE/Game112Client/assets/scripts/ConfigConst.ts $BUILD_NUMBER $SHORT_GIT_COMMIT

$WORKSPACE/ci/build_ios.sh

echo "Start Edit Info.plist..."

SCHEME="Game112Client-mobile"
echo SCHEME=$SCHEME

VERSION="1.0.1"
echo VERSION=$VERSION

InfoPlist_PATH="$WORKSPACE/Game112Client/build/ios/proj/CMakeFiles/$SCHEME.dir/Info.plist"
echo InfoPlist_PATH=$InfoPlist_PATH

/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '${VERSION}'" $InfoPlist_PATH
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion '${BUILD_NUMBER}'" $InfoPlist_PATH
/usr/libexec/PlistBuddy -c "Set :SHORT_COMMIT_HASH '${SHORT_GIT_COMMIT}'" $InfoPlist_PATH

#echo "Delete old xcarchive..."
#rm -r -f $WORKSPACE/Game112Client/build/*.xcarchive

echo "Start Xcode Archive..."

XCARCHIVE_FILE_NAME="BlockJam_v${VERSION}_b${BUILD_NUMBER}_${SHORT_GIT_COMMIT}.xcarchive"

xcodebuild archive \
-workspace $WORKSPACE/Game112Client/build/ios/proj/Game112Client.xcworkspace \
-scheme $SCHEME \
-archivePath $WORKSPACE/$XCARCHIVE_FILE_NAME \
-allowProvisioningUpdates

echo "All completed!"